from ssq import SSQDataset, NeuralNetwork
from torch.utils.data import random_split, DataLoader
from torch import nn, optim, no_grad, Tensor
import torch

def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)
    model.train()
    success = 0
    total = 0
    for batch, (X, y) in enumerate(dataloader):
        pred = model(X)
        loss = loss_fn(pred, y)

        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

        success = success + (pred.argmax(1) == y.argmax(1)).type(torch.float).sum().item()
        total = total + len(y)

        if batch % 6 == 0 or (batch) * dataloader.batch_size + len(X) == size:
            loss, current = loss.item(), (batch) * dataloader.batch_size + len(X)
            print(f"Train loss: {loss:>7f}, accuracy: {(100*success/total):>0.1f}% [{current:>5d}/{size:>5d}]")

def test(dataloader, model, loss_fn):
    model.eval()
    success = 0
    total = 0
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    test_loss = 0
    with no_grad():
        for X, y in dataloader:
            pred = model(X)
            test_loss += loss_fn(pred, y).item()

            success = success + (pred.argmax(1) == y.argmax(1)).type(torch.float).sum().item()
            total = total + len(y)

    test_loss /= num_batches
    print(f"Test  loss: {test_loss:>8f}, accuracy: {(100*success/total):>0.1f}%\n")

def run_train():
    sample = 21
    dataset_object = SSQDataset(sample)
    train_data_size = int(len(dataset_object) * 0.90)
    test_data_size = len(dataset_object) - train_data_size
    train_data, test_data = random_split(dataset_object, [train_data_size, test_data_size])

    batch_size = 100
    train_data_loader = DataLoader(train_data, batch_size=batch_size)
    test_data_loader = DataLoader(test_data, batch_size=batch_size)

    model = NeuralNetwork()
    loss_fn = nn.MSELoss()
    optimizer = optim.Adam(model.parameters(), lr=0.001)

    epochs = 3
    for t in range(epochs):
        print(f"Epoch {t+1}\n-------------------------------")
        train(train_data_loader, model, loss_fn, optimizer)
        test(test_data_loader, model, loss_fn)
    print("Done!")

    # 预测
    model.eval()
    with no_grad():
        dataset_object = SSQDataset(sample)
        x, y = dataset_object[len(dataset_object)-1]
        inputs = (x + y).numpy().tolist()[-sample:]
        outputs = []
        for i in range(7):
            y = model(Tensor([inputs]))
            for item in outputs:
                y[0][item] = -1e6
            outputs.append(y.argmax(1).item())
            if 6 == i:
                for e in range(33 - 16):
                    y[0][16 + e] = -1e6
                outputs.append(y.argmax(1).item())
        result = [str(i + 1) for i in outputs]
        print("预测结果（红球+篮球）：" + ",".join(result))

if __name__ == '__main__':
    run_train()
